﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VietPublisher.BSL.BK;
using VietPublisher.Repository.Repositories.Concrete;


namespace VietPublisher.Repositories.Interface
{
    public class PublisherRepository : BaseRepository, IPublisherRepository
    {
        #region constructor
        public PublisherRepository() { }
        #endregion


        public List<T_BK_Publisher> GetPublisherList()
        {
            var publishers = from c in ContextBookStore.T_BK_Publisher select c;
            return publishers.ToList<T_BK_Publisher>();
        }

        public T_BK_Publisher GetPublisherByBook(int bookID)
        {
            var publisher = (
                            from pl in ContextBookStore.T_BK_Publisher
                            join bk in ContextBookStore.T_BK_Book
                            on pl.PublisherID equals bk.PublisherID
                            where bk.BookID == bookID
                            select pl
                            )
                            .SingleOrDefault();
            return publisher;
        }

        public bool ChangePublisherInfo(T_BK_Publisher publisher)
        {
            ContextBookStore.T_BK_Publisher.ApplyCurrentValues(publisher);
            int returnvalue = ContextBookStore.SaveChanges();
            return returnvalue > 0 ? true : false;
        }

        public int CreatePublisher(T_BK_Publisher publisher)
        {
            ContextBookStore.T_BK_Publisher.AddObject(publisher);
            ContextBookStore.SaveChanges();
            int rowEffect = publisher.PublisherID;
            return rowEffect;
        }

        public string GetPublisherNameByBook(int bookID)
        {
            string publisherName = string.Empty;
            var publisher =
                           (
                           from pl in ContextBookStore.T_BK_Publisher
                           join bk in ContextBookStore.T_BK_Book
                           on pl.PublisherID equals bk.PublisherID
                           select pl
                           )
                                     .SingleOrDefault();
            if (publisher != null)
            {
                publisherName = publisher.PublisherName;
            }

            return publisherName;
        }

        public int GetPublisherIDByBook(int bookID)
        {
            int publisherID = 0;
            var publisher = ContextBookStore.T_BK_Book.Where(p => p.BookID == bookID).FirstOrDefault();
            if (publisher != null)
            {
                publisherID = publisher.PublisherID.Value;
            }
            return publisherID;
        }

    }//close class
}//close namespace
